import axios from 'axios';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { useEffect, useState, useReducer } from 'react';
import { initialCartState, cartReducer } from './reducers/cartReducer';
import Header from './components/Header';
import Home from './components/Home';
import NotFound from './components/NotFound';
import Details from './components/Details';
import DetailItem from './components/DetailItem';
import Cart from './components/Cart';

const storageKey = 'cart';

function App() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    axios.get('/api/items')
      .then((result) => setItems(result.data))
      .catch((error) => console.error(error));
  }, []);
  const [cart, dispatch] = useReducer(
    cartReducer,
    initialCartState,
    (initialState) => {
      try {
        const savedCart = JSON.parse(localStorage.getItem(storageKey));
        return savedCart || initialState;
      } catch (error) {
        console.error(error);
        return initialState;
      }
    },
  );
  useEffect(() => {
    localStorage.setItem(storageKey, JSON.stringify(cart));
  }, [cart]);
  return (
    <Router>
      <Header cart={cart} />
      {items.length === 0
        ? <div>Loading...</div>
        : (
          <Routes>
            <Route path="/cart" element={<Cart cart={cart} items={items} dispatch={dispatch} />} />
            <Route path="/details" element={<Details items={items} />}>
              <Route path=":id" element={<DetailItem items={items} dispatch={dispatch} />} />
              <Route index element={<div>No Item Selected.</div>} />
            </Route>
            <Route path="/" element={<Home items={items} />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        )}
    </Router>
  );
}

export default App;
